<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 基础表格 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除</el-button>
                <el-select v-model="query.role" placeholder="角色" class="handle-select mr10">
                    <el-option key="1" label="学生" value="学生"></el-option>
                    <el-option key="2" label="老师" value="老师"></el-option>
                </el-select>
                <el-input v-model="query.username" placeholder="用户名" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" @click="handleReset">重置</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="username" label="用户名" width="100" align="center"></el-table-column>
                <!-- <el-table-column prop="password" label="密码" width="100" align="center"></el-table-column> -->
                <el-table-column prop="phone" label="手机号码" width="120" align="center"></el-table-column>
                <el-table-column prop="college" label="学院" width="120" align="center"></el-table-column>
                <el-table-column label="角色" @row-click="scope(scope)" width="50" align="center">
                    <template slot-scope="scope" @click="scope(scope)">{{ +scope.row.role === 1 ? '学生' : '老师' }}</template>
                </el-table-column>
                <el-table-column label="性别" @row-click="scope(scope)" width="50" align="center">
                    <template slot-scope="scope" @click="scope(scope)">{{ +scope.row.sex === 1 ? '男' : '女' }}</template>
                </el-table-column>
                <!-- <el-table-column label="头像(查看大图)" align="center">
                    <template slot-scope="scope">
                        <el-image
                            v-if="scope.row.headPic.content"
                            class="table-td-thumb"
                            :src="scope.row.headPic.content"
                            :preview-src-list="[scope.row.headPic.content]"
                        ></el-image>
                        <el-image
                            v-else
                            class="table-td-thumb"
                            src="static / images / headPic.png"
                            preview-src-list="static / images / headPic.png"
                        ></el-image>
                    </template>
                </el-table-column> -->
                <el-table-column label="被举报次数" @row-click="scope(scope)" width="100" align="center">
                    <template slot-scope="scope" @click="scope(scope)">{{ scope.row.reportNum }}次</template>
                </el-table-column>
                <el-table-column label="审核状态" @row-click="scope(scope)" width="80" align="center">
                    <template slot-scope="scope" @click="scope(scope)">{{ +scope.row.status === 1 ? '已通过' : '不通过' }}</template>
                </el-table-column>
                <el-table-column prop="email" label="邮箱" width="200" align="center"></el-table-column>
                <el-table-column prop="applyTime" label="注册时间" width="200" align="center"></el-table-column>
                <el-table-column label="最后登录时间" width="200" align="center">
                    <template slot-scope="scope">{{
                        scope.row.lastSignInTime !== null ? scope.row.lastSignInTime : '未曾登陆过'
                    }}</template>
                </el-table-column>
                <el-table-column prop="safetyProblem1" label="安全问题1" width="120" align="center"></el-table-column>
                <el-table-column prop="safetyAnswer1" label="安全问题答案1" width="120" align="center"></el-table-column>
                <el-table-column prop="safetyProblem2" label="安全问题2" width="120" align="center"></el-table-column>
                <el-table-column prop="safetyAnswer2" label="安全问题答案2" width="120" align="center"></el-table-column>
                <el-table-column label="操作" width="50" align="center">
                    <template slot-scope="scope">
                        <el-dropdown>
                            <span>
                                <i class="el-icon-lx-more"></i>
                            </span>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item><el-button type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button></el-dropdown-item>
                                <el-dropdown-item><el-button type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button></el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
            <el-form ref="form" :model="form" label-width="120px" :rules="rules">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="form.phone"></el-input>
                </el-form-item>
                <el-form-item label="学院" prop="college">
                    <el-input v-model="form.college"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <el-radio v-model="form.role" :label="+1">学生</el-radio>
                    <el-radio v-model="form.role" :label="+2">老师</el-radio>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio v-model="form.sex" label="1">男</el-radio>
                    <el-radio v-model="form.sex" label="2">女</el-radio>
                </el-form-item>
                <!-- <el-form-item label="被举报次数">
                    <el-input v-model="form.reportNum"></el-input>
                </el-form-item> -->
                <!-- <el-form-item label="审核状态" prop="status">
                    <el-radio v-model="form.status" :label="+1">通过</el-radio>
                    <el-radio v-model="form.status" :label="+2">不通过</el-radio>
                </el-form-item> -->
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email"></el-input>
                </el-form-item>
                <!-- <el-form-item label="注册时间">
                    <el-input v-model="form.applyTime"></el-input>
                </el-form-item>
                <el-form-item label="最后登录时间">
                    <el-input v-model="form.lastSignInTime"></el-input>
                </el-form-item> -->
                <el-form-item label="安全问题1" prop="safetyProblem1">
                    <el-input v-model="form.safetyProblem1"></el-input>
                </el-form-item>
                <el-form-item label="安全问题答案1" prop="safetyAnswer1">
                    <el-input v-model="form.safetyAnswer1"></el-input>
                </el-form-item>
                <el-form-item label="安全问题2" prop="safetyProblem2">
                    <el-input v-model="form.safetyProblem2"></el-input>
                </el-form-item>
                <el-form-item label="安全问题答案2" prop="safetyAnswer2">
                    <el-input v-model="form.safetyAnswer2"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelEdit(form)">取 消</el-button>
                <el-button type="primary" @click="saveEdit(form)">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { fetchData } from '../../../api/index';
import { getAllUser, setUser, removeUser } from '@/views/api/api.js';
export default {
    name: 'userManagement',
    data() {
        return {
            query: {
                role: '',
                username: '',
                pageIndex: 1,
                pageSize: 10
            },
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            rules: {
                username: [{ required: true, message: '用户名不能为空！', trigger: 'blur' }],
                password: [{ required: true, message: '密码不能为空！', trigger: 'blur' }],
                phone: [{ required: true, message: '手机号码不能为空！', trigger: 'blur' }],
                college: [{ required: true, message: '学院不能为空！', trigger: 'blur' }],
                role: [{ required: true, message: '角色不能为空！', trigger: 'blur' }],
                sex: [{ required: true, message: '性别不能为空！', trigger: 'blur' }],
                status: [{ required: true, message: '审核状态不能为空！', trigger: 'blur' }],
                email: [{ required: true, message: '邮箱不能为空！', trigger: 'blur' }],
                safetyProblem1: [{ required: true, message: '安全问题1不能为空！', trigger: 'blur' }],
                safetyAnswer1: [{ required: true, message: '安全问题答案1不能为空！', trigger: 'blur' }],
                safetyProblem2: [{ required: true, message: '安全问题2不能为空！', trigger: 'blur' }],
                safetyAnswer2: [{ required: true, message: '安全问题答案2不能为空！', trigger: 'blur' }]
            }
        };
    },
    created() {
        this.getData();
    },
    methods: {
        // 获取所有的用户数据
        getData() {
            // fetchData(this.query).then(res => {
            //     console.log(res);
            //     this.tableData = res.list;
            //     this.pageTotal = res.pageTotal || 50;
            // });
            getAllUser(this.query).then((res) => {
                if (!res.data.code) {
                    // 成功
                    this.tableData = res.data.Info;
                    this.pageTotal = res.data.total;
                    for (let j = 0; j < this.tableData.length; j++) {
                        this.tableData[j].applyTime = this.utc2beijing(this.tableData[j].applyTime);
                        if (this.tableData[j].lastSignInTime) {
                            this.tableData[j].lastSignInTime = this.utc2beijing(this.tableData[j].lastSignInTime);
                        }
                    }
                } else {
                    // 失败
                    this.tableData = res.data.Info;
                    this.pageTotal = res.data.total;
                    this.$message({
                        showClose: true,
                        message: res.data.msg,
                        type: 'error'
                    });
                }
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        // 触发重置按钮
        handleReset() {
            this.query = {
                role: '',
                username: '',
                pageIndex: 1,
                pageSize: 10
            };
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.multipleSelection = [];
                    this.multipleSelection.push(row._id);
                    let params = {
                        multipleSelection: this.multipleSelection
                    };
                    removeUser(params).then((res) => {
                        if (res.data.code) {
                            // Toast.fail(res.data.msg)
                        } else {
                            this.$message.success('删除成功');
                            this.getData();
                            this.multipleSelection = [];
                        }
                    });
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = [];
            for (let i = 0; i < val.length; i++) {
                this.multipleSelection.push(val[i]._id);
            }
        },
        delAllSelection() {
            // 二次确认删除
            if (this.multipleSelection.length > 0) {
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        let params = {
                            multipleSelection: this.multipleSelection
                        };
                        removeUser(params).then((res) => {
                            if (res.data.code) {
                                // Toast.fail(res.data.msg)
                            } else {
                                this.$message.success('删除成功');
                                this.getData();
                                this.multipleSelection = [];
                            }
                        });
                    })
                    .catch(() => {});
            } else {
                this.$message.warning('请选择要删除的用户');
            }
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = JSON.parse(JSON.stringify(row));
            console.log(row);
            this.editVisible = true;
        },
        // 保存编辑
        saveEdit(form) {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    let params = {
                        id: this.form._id,
                        password: this.form.password,
                        phone: this.form.phone,
                        college: this.form.college,
                        role: this.form.role,
                        sex: this.form.sex,
                        email: this.form.email,
                        safetyProblem1: this.form.safetyProblem1,
                        safetyProblem2: this.form.safetyProblem2,
                        safetyAnswer1: this.form.safetyAnswer1,
                        safetyAnswer2: this.form.safetyAnswer2
                    };
                    setUser(params).then((res) => {
                        if (res.data.code) {
                            this.$message({
                                showClose: true,
                                message: res.data.msg,
                                type: 'error'
                            });
                        } else {
                            this.editVisible = false;
                            this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                            this.$set(this.tableData, this.idx, this.form);
                        }
                    });
                } else {
                    return false;
                }
            });
        },
        cancelEdit(form) {
            this.editVisible = false;
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        },
        scope(scope) {
            console.log(scope);
        },
        // 时间戳转为时间
        timestampToTime(timestamp) {
            var date = new Date(timestamp); // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
            var Y = date.getFullYear() + '年';
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
            var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '日 ';
            var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
            var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
            var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
            return Y + M + D + h + m + s;
        },
        // UTC时间格式转通用格式时间
        // eslint-disable-next-line camelcase
        utc2beijing(utc_datetime) {
            // 转为正常的时间格式 年-月-日 时:分:秒
            // eslint-disable-next-line camelcase
            var T_pos = utc_datetime.indexOf('T');
            // eslint-disable-next-line camelcase
            var Z_pos = utc_datetime.indexOf('Z');
            // eslint-disable-next-line camelcase
            var year_month_day = utc_datetime.substr(0, T_pos);
            // eslint-disable-next-line camelcase
            var hour_minute_second = utc_datetime.substr(
                // eslint-disable-next-line camelcase
                T_pos + 1,
                // eslint-disable-next-line camelcase
                Z_pos - T_pos - 1
            );
            // eslint-disable-next-line camelcase
            var new_datetime = year_month_day + ' ' + hour_minute_second; // 2017-03-31 08:02:06

            // 处理成为时间戳
            // eslint-disable-next-line no-use-before-define
            timestamp = new Date(Date.parse(new_datetime));
            // eslint-disable-next-line no-use-before-define
            timestamp = timestamp.getTime();
            // eslint-disable-next-line no-use-before-define
            timestamp = timestamp / 1000;

            // 增加8个小时，北京时间比utc时间多八个时区
            // eslint-disable-next-line no-use-before-define
            var timestamp = timestamp + 8 * 60 * 60;

            // 时间戳转为时间
            // eslint-disable-next-line camelcase
            var beijing_datetime = this.timestampToTime(timestamp * 1000);
            // eslint-disable-next-line camelcase
            return beijing_datetime; // 2017-03-31 16:02:06
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
